import axios, {
  AxiosResponse,
  AxiosInstance,
  AxiosRequestConfig,
  AxiosError
} from 'axios'

import { options } from '@/config'

class Http {
  private baseURL: string
  private timeout: number
  constructor(baseUrl: string) {
    this.baseURL = baseUrl
    this.timeout = 3000
  }
  setInterceptor(instance: AxiosInstance) {
    instance.interceptors.request.use((config: AxiosRequestConfig) => {
      return config
    })
    instance.interceptors.response.use(
      (res: AxiosResponse) => {
        if (res.status == 200) {
          return Promise.resolve(res.data)
        } else {
          return Promise.reject(res)
        }
      },
      (err: AxiosError) => {
        return Promise.reject(err)
      }
    )
  }
  mergeOptions(options: AxiosRequestConfig) {
    return {
      baseURL: this.baseURL,
      timeout: this.timeout,
      ...options
    }
  }
  request(options: AxiosRequestConfig) {
    const instance = axios.create()
    const opts = this.mergeOptions(options)
    this.setInterceptor(instance)
    return instance(opts)
  }
  get(url: string, config: AxiosRequestConfig = {}) {
    return this.request({
      method: 'get',
      url: url,
      ...config
    })
  }
  post(url: string, data: any) {
    return this.request({
      method: 'post',
      url,
      data
    })
  }
}

export default new Http(options.baseURL)
